import java.util.Deque;
import java.util.LinkedList;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=111 lang=java
 *
 * [111] 二叉树的最小深度
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        // int res=0;
        // if(root==null) return res;
        // Deque<TreeNode> que=new LinkedList<>();
        // que.offer(root);
        // while(!que.isEmpty()){
        //     int size=que.size();
        //     res++;
        //     for(int i=0;i<size;i++){
        //         TreeNode front=que.poll();
        //         if(front.left==null&&front.right==null) return res;
        //         if(front.left!=null){
        //             que.offer(front.left);
        //         }
        //         if(front.right!=null){
        //             que.offer(front.right);
        //         }
        //     }
        // }
        // return res;
        //递归法
        if(root==null) return 0;
        int rightDepth=minDepth(root.right);
        int leftDepeth=minDepth(root.left);
        if(root.left==null&&root.right!=null){
            return 1+rightDepth;
        }
        if(root.left!=null&&root.right==null){
            return 1+leftDepeth;
        }
        return 1+Math.min(leftDepeth, rightDepth);
    }
}
// @lc code=end

